﻿<%@ WebHandler Language="C#" Class="PeriodicCheckHandler" %>

/*Description: 周期性检验处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:2023-01-05
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.IO;
using System.Collections;
using NPOI.SS.UserModel;

public class PeriodicCheckHandler : IHttpHandler, IRequiresSessionState
{
    string fileBasePath = "/InSiteWebApplication/Temp2/ImportTemp/PeriodicCheck/";
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    PeriodicCheckBusiness pcbusiness = new PeriodicCheckBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(ResMessage(false, "数据过期，请重新登录"));
                return;
            }
            var action = context.Request["action"].ToString();
            switch (action)
            {
                case "InitPageData": //初始化页面数据
                    InitPageData(context);
                    break;
                case "UploadCheckFile": //上传周期性检验数据
                    UploadCheckFile(context);
                    break;
                case "GetPeriodicCheckList": //获取周期性检验列表
                    GetPeriodicCheckList(context);
                    break;
                case "GetPeriodicCheckApplyList": //获取委托单列表
                    GetPeriodicCheckApplyList(context);
                    break;
                case "CreatePeriodicCheckData": //添加周期性检验数据（弹窗保存）
                    CreatePeriodicCheckData(context);
                    break;
                case "UpdatePeriodicCheckStatus": //更新周期性检测数据状态（删除，启停）
                    UpdatePeriodicCheckStatus(context);
                    break;
                case "CreatePeriodicCheckApply": //添加提起委托计量申请
                    CreatePeriodicCheckApply(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(ResMessage(false, "系统报错：" + ex.Message));
        }
    }

    /// <summary>
    /// 初始化页面数据
    /// </summary>
    /// <param name="context"></param>
    public void InitPageData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        //获取查询工区
        DataTable dtWorkCenter = commonBusiness.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        var drs = dtWorkCenter.Select(" notes is null or notes <>'已注销' ");
        if (drs.Length > 0)
        {
            dtWorkCenter = drs.CopyToDataTable();
        }
        dtWorkCenter.TableName = "dtWorkCenter";
        DataRow dr = dtWorkCenter.NewRow();
        dr["WORKCENTERID"] = "";
        dr["WORKCENTERNAME"] = "请选择";
        dtWorkCenter.Rows.InsertAt(dr, 0);
        result.DBTable = dtWorkCenter;
        //获取下载模板
        result.ReturnData = "http://" + context.Request.Url.Host + context.Request.ApplicationPath + "/Temp2/导入模板/周期性检验导入模板.xlsx";
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 获取委托单列表
    /// </summary>
    /// <param name="context"></param>
    public void GetPeriodicCheckApplyList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("PageNumber", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("PeriodicCheckBaseDataId", context.Request["periodicCheckBaseDataId"].ToString());
        uMESProcessResult result = pcbusiness.GetPeriodicCheckApplyDataByPage(para);
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 添加提起委托计量申请
    /// </summary>
    /// <param name="context"></param>
    public void CreatePeriodicCheckApply(HttpContext context)
    {
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDt"].ToString());
        if (paramDt.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "未选择数据"));
            return;
        }
        //计算单号
        string seleSql = @"SELECT * FROM(
            SELECT p.applyno FROM PeriodicCheckApply p
            WHERE p.isuse = 0 ORDER BY p.Createdate DESC,p.applyno DESC) WHERE ROWNUM =1";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(seleSql);
        string checkNo = "WTJL" + DateTime.Now.ToString("yyyyMM");
        int checkNo_num = 1;//默认为1
        if (dt.Rows.Count > 0)
        {
            if (dt.Rows[0]["applyno"].ToString().Contains(checkNo))
            {
                checkNo_num = int.Parse(dt.Rows[0]["applyno"].ToString().Replace(checkNo, "")) + 1;
            }
        }
        List<ExcuteEntity> listEx = new List<ExcuteEntity>();
        bool res = true;
        string msg = "生成成功";
        //保存数据
        seleSql = "SELECT 1 FROM PeriodicCheckApply p WHERE p.periodiccheckbasedataid = '{0}' AND p.isuse = 0 AND p.status = '1'";
        foreach (DataRow item in paramDt.Rows)
        {
            if (DatabaseHelper.GetSingle(string.Format(seleSql, item["periodiccheckbasedataid"].ToString())) != null)
            {
                res = false;
                msg = "存在检测中的数据";
                break;
            }
            ExcuteEntity exuteEntity = new ExcuteEntity("PeriodicCheckApply", ExcuteEntity.ExcuteTypeEnum.insert);
            List<FieldEntity> excuteFieldList = new List<FieldEntity>();
            excuteFieldList.Add(new FieldEntity("PeriodicCheckApplyID", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("PeriodicCheckBaseDataID", item["periodiccheckbasedataid"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("ApplyNo", checkNo + checkNo_num.ToString().PadLeft(4, '0'), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Status", 1, FieldEntity.FieldTypeEnum.Numer));
            excuteFieldList.Add(new FieldEntity("Isuse", 0, FieldEntity.FieldTypeEnum.Numer));
            excuteFieldList.Add(new FieldEntity("CreateDate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
            excuteFieldList.Add(new FieldEntity("CreateEmpID", m_UserInfo.EmployeeID.ToString(), FieldEntity.FieldTypeEnum.Str));
            exuteEntity.ExcuteFileds = excuteFieldList;
            listEx.Add(exuteEntity);
            checkNo_num++;
        }
        if (res)
        {
            if (!DatabaseHelper.ExecuteDataByEntitys(listEx))
            {
                res = false; msg = "保存出错";
            }
        }
        context.Response.Write(ResMessage(res, msg));
    }

    /// <summary>
    /// Excel批量上传
    /// </summary>
    /// <param name="context"></param>
    public void UploadCheckFile(HttpContext context)
    {
        string fpath = string.Empty;
        try
        {
            if (!Directory.Exists(context.Server.MapPath(fileBasePath)))
            {
                Directory.CreateDirectory(context.Server.MapPath(fileBasePath));
            }
            var files = context.Request.Files;
            HttpPostedFile file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string IsXls = Path.GetExtension(file.FileName);
            string fileName = Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + IsXls;
            fpath = context.Server.MapPath(fileBasePath + fileName);
            file.SaveAs(fpath);//保存文件
            //读取文件工作薄
            IWorkbook workbook = uLMS_CommonFunction.GetWorkbookObj(fpath);
            if (workbook == null)
            {
                DeleteFile(fpath);
                context.Response.Write(ResMessage(false, "解析Excel出错"));
                return;
            }
            DataTable dt = uLMS_CommonFunction.ExcelImportToDataTable(workbook);//获取上传表格
            if (dt.Rows.Count == 0)
            {
                DeleteFile(fpath);
                context.Response.Write(ResMessage(false, "未获取Excel表格数据"));
                return;
            }
            //保存数据
            bool res = true;
            string msg = "保存成功";
            if (!IsVaildImportPeriodicCheck(ref dt, ref msg))
            {
                DeleteFile(fpath);
                context.Response.Write(ResMessage(false, msg));
                return;
            }
            List<ExcuteEntity> listEx = new List<ExcuteEntity>();
            foreach (DataRow item in dt.Rows)
            {
                ExcuteEntity exuteEntity = new ExcuteEntity("PeriodicCheckBaseData", ExcuteEntity.ExcuteTypeEnum.insert);
                List<FieldEntity> excuteFieldList = new List<FieldEntity>();
                excuteFieldList.Add(new FieldEntity("PeriodicCheckBaseDataID", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("ProductName", item["零件号"].ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("SpecNo", item["工序号"].ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("Opdesc", item["工序名称"].ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("DetectionType", item["检测类型"].ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("EffectiveType", item["有效类型"].ToString(), FieldEntity.FieldTypeEnum.Str));

                if (!string.IsNullOrWhiteSpace(item["有效类型计数"].ToString()))
                {
                    excuteFieldList.Add(new FieldEntity("EffectiveCount", item["有效类型计数"].ToString(), FieldEntity.FieldTypeEnum.Numer));
                }
                if (!string.IsNullOrWhiteSpace(item["剩余数量"].ToString()))
                {
                    excuteFieldList.Add(new FieldEntity("SurplusQty", item["剩余数量"].ToString(), FieldEntity.FieldTypeEnum.Numer));
                }
                if (!string.IsNullOrWhiteSpace(item["到期日期"].ToString()))
                {
                    excuteFieldList.Add(new FieldEntity("DueDate", item["到期日期"].ToString(), FieldEntity.FieldTypeEnum.DateTime));
                }
                excuteFieldList.Add(new FieldEntity("FactoryID", m_UserInfo.FactoryID, FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("WorkCenterID", item["workCenterID"].ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("TeamID", item["teamID"].ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("Notes", item["备注"].ToString(), FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("CreateEmpID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
                excuteFieldList.Add(new FieldEntity("CreateDate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
                excuteFieldList.Add(new FieldEntity("Isuse", 0, FieldEntity.FieldTypeEnum.Numer));
                excuteFieldList.Add(new FieldEntity("IsEnable", 1, FieldEntity.FieldTypeEnum.Numer));
                exuteEntity.ExcuteFileds = excuteFieldList;
                listEx.Add(exuteEntity);
            }
            if (!DatabaseHelper.ExecuteDataByEntitys(listEx))
            {
                res = false;
                msg = "保存出错";
            }
            DeleteFile(fpath);
            context.Response.Write(ResMessage(res, msg));
        }
        catch (Exception e)
        {
            DeleteFile(fpath);
            context.Response.Write(ResMessage(false, "系统报错：" + e.Message));
        }
    }
    /// <summary>
    /// 验证导入保存
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    private bool IsVaildImportPeriodicCheck(ref DataTable dt, ref string msg)
    {
        bool res = true;
        string[] headName = { "零件号", "有效类型", "工序号", "工序名称", "检测类型", "有效类型" };
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow item = dt.Rows[i];
            foreach (string name in headName)
            {
                if (string.IsNullOrWhiteSpace(item[name].ToString()))
                {
                    msg = "第" + (i + 2) + "行没有填写" + name;
                    res = false;
                    break;
                }
            }
            if (res)
            {
                //验证是否有效插入
                if (!pcbusiness.IsVaildPeriodicCheck(item["零件号"].ToString(), item["工序号"].ToString(), item["工序名称"].ToString(), ref msg))
                {
                    res = false;
                    break;
                }
                Tuple<bool,string,string> resT = pcbusiness.IsVaildWorkCenter(m_UserInfo.FactoryID,item["工区"].ToString(), item["班组"].ToString());
                if (!resT.Item1)
                {
                    msg = "第" + (i + 2) + "行未找到相应的工区和班组";
                    res = false;
                    break;
                }
                item["工区"] = resT.Item2; item["班组"] = resT.Item3;//更改工区班组为对应的ID
                if (item["有效类型"].ToString() == "件")
                {
                    if (string.IsNullOrWhiteSpace(item["有效类型计数"].ToString()))
                    {
                        msg = "有效类型为件，有效类型计数不能为空（第" + (i + 2) + "行）";
                        res = false;
                        break;
                    }
                    if (string.IsNullOrWhiteSpace(item["剩余数量"].ToString()))
                    {
                        item["剩余数量"] = item["有效类型计数"].ToString();//如果没有填写剩余数据，则等于有效数量
                    }
                    if (int.Parse(item["剩余数量"].ToString()) > int.Parse(item["有效类型计数"].ToString()))
                    {
                        msg = "有效类型为件，剩余数量不能大于有效类型计数（第" + (i + 2) + "行）";
                        res = false;
                        break;
                    }
                    item["到期日期"] = "";
                }
                else if (item["有效类型"].ToString() == "天")
                {
                    if (string.IsNullOrWhiteSpace(item["到期日期"].ToString()))
                    {
                        msg = "有效类型为天，到期日期不能为空（第" + (i + 2) + "行）";
                        res = false;
                        break;
                    }
                    item["有效类型计数"] = "";
                    item["剩余数量"] = "";
                }
                else
                {
                    msg = "第" + (i + 2) + "行有效类型填写错误，必须为件或者天";
                    res = false;
                    break;
                }
            }
        }
        dt.AcceptChanges();
        return res;
    }

    /// <summary>
    /// 添加周期性检测数据（弹窗）
    /// </summary>
    public void CreatePeriodicCheckData(HttpContext context)
    {
        bool res = true;
        string msg = "添加成功";
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (paramDt.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "无添加数据"));
            return;
        }
        DataRow drItem = paramDt.Rows[0];
        if (!pcbusiness.IsVaildPeriodicCheck(drItem["productName"].ToString(), drItem["specNo"].ToString(), drItem["opdesc"].ToString(), ref msg))//验证是否有效插入
        {
            context.Response.Write(ResMessage(false, msg));
            return;
        }
        if (drItem["effectiveType"].ToString() == "件")
        {
            if (string.IsNullOrWhiteSpace(drItem["effectiveCount"].ToString()))
            {
                msg = "有效类型为件，有效类型计数不能为空";
                res = false;
            }
            if (res && string.IsNullOrWhiteSpace(drItem["surplusQty"].ToString()))
            {
                drItem["surplusQty"] = drItem["effectiveCount"].ToString();//如果没有填写剩余数据，则等于有效数量
            }
            if (res && (int.Parse(drItem["surplusQty"].ToString()) > int.Parse(drItem["effectiveCount"].ToString())))
            {
                msg = "有效类型为件，剩余数量不能大于有效类型计数";
                res = false;
            }
            drItem["dueDate"] = "";
        }
        else if (drItem["effectiveType"].ToString() == "天")
        {
            if (string.IsNullOrWhiteSpace(drItem["dueDate"].ToString()))
            {
                msg = "有效类型为天，到期日期不能为空";
                res = false;
            }
            drItem["effectiveCount"] = "";
            drItem["surplusQty"] = "";
        }
        else
        {
            msg = "有效类型填写错误，必须为件或者天";
            res = false;
        }
        if (res)
        {
            ExcuteEntity exuteEntity = new ExcuteEntity("PeriodicCheckBaseData", ExcuteEntity.ExcuteTypeEnum.insert);
            List<FieldEntity> excuteFieldList = new List<FieldEntity>();
            excuteFieldList.Add(new FieldEntity("PeriodicCheckBaseDataID", Guid.NewGuid().ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("ProductName", drItem["productName"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("SpecNo", drItem["specNo"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Opdesc", drItem["opdesc"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("DetectionType", drItem["detectionType"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("EffectiveType", drItem["effectiveType"].ToString(), FieldEntity.FieldTypeEnum.Str));

            if (!string.IsNullOrWhiteSpace(drItem["effectiveCount"].ToString()))
            {
                excuteFieldList.Add(new FieldEntity("EffectiveCount", drItem["effectiveCount"].ToString(), FieldEntity.FieldTypeEnum.Numer));
            }
            if (!string.IsNullOrWhiteSpace(drItem["surplusQty"].ToString()))
            {
                excuteFieldList.Add(new FieldEntity("SurplusQty", drItem["surplusQty"].ToString(), FieldEntity.FieldTypeEnum.Numer));
            }
            if (!string.IsNullOrWhiteSpace(drItem["dueDate"].ToString()))
            {
                excuteFieldList.Add(new FieldEntity("DueDate", drItem["dueDate"].ToString(), FieldEntity.FieldTypeEnum.DateTime));
            }
            excuteFieldList.Add(new FieldEntity("FactoryID", m_UserInfo.FactoryID, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("WorkCenterID", drItem["workCenterID"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("TeamID", drItem["teamID"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("Notes", drItem["notes"].ToString(), FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("CreateEmpID", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
            excuteFieldList.Add(new FieldEntity("CreateDate", DateTime.Now, FieldEntity.FieldTypeEnum.DateTime));
            excuteFieldList.Add(new FieldEntity("Isuse", 0, FieldEntity.FieldTypeEnum.Numer));
            excuteFieldList.Add(new FieldEntity("IsEnable", 1, FieldEntity.FieldTypeEnum.Numer));
            exuteEntity.ExcuteFileds = excuteFieldList;
            if (!DatabaseHelper.ExecuteDataByEntity(exuteEntity))
            {
                res = false;
                msg = "添加失败";
            }
        }
        context.Response.Write(ResMessage(res, msg));
    }

    /// <summary>
    /// 更新周期性检测数据状态（删除，启停）
    /// </summary>
    /// <param name="context"></param>
    public void UpdatePeriodicCheckStatus(HttpContext context)
    {
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDt"].ToString());
        int operaType = int.Parse(context.Request["operaType"].ToString());//操作类型
        if (paramDt.Rows.Count == 0)
        {
            context.Response.Write(ResMessage(false, "未选择数据"));
            return;
        }
        context.Response.Write(ResMessage(pcbusiness.UpdatePeriodicCheckStatus(paramDt, operaType, m_UserInfo)));
    }

    /// <summary>
    /// 获取周期性检测项列表
    /// </summary>
    /// <param name="context"></param>
    public void GetPeriodicCheckList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("PageNumber", context.Request["pageIndex"].ToString());
        para.Add("PageSize", context.Request["pageSize"].ToString());
        para.Add("ProductName", context.Request["productName"].ToString());
        para.Add("SpecNo", context.Request["specNo"].ToString());
        para.Add("SpecDesc", context.Request["specDesc"].ToString());
        para.Add("Status", context.Request["status"].ToString());
        para.Add("WorkCenterID", context.Request["workCenterID"].ToString());
        para.Add("TeamID", context.Request["teamID"].ToString());
        uMESProcessResult result = pcbusiness.GetPeriodicCheckListByPage(para);
        context.Response.Write(ResMessage(result));
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="fpath">文件地址</param>
    private void DeleteFile(string fpath)
    {
        if (File.Exists(fpath))
        {
            new FileInfo(fpath).Attributes = FileAttributes.Normal;
            File.Delete(fpath);
        }
    }

    /// <summary>
    /// 返回提示消息
    /// </summary>
    /// <param name="res"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    private string ResMessage(bool res, string msg)
    {
        uMESProcessResult result = new uMESProcessResult() { Message = msg, Result = res };
        return JsonConvert.SerializeObject(result);
    }

    /// <summary>
    /// 返回提示消息(带返回数据)
    /// </summary>
    /// <param name="res"></param>
    /// <param name="msg"></param>
    /// <param name="dt"></param>
    /// <returns></returns>
    private string ResMessage(bool res, string msg, DataTable dt)
    {
        uMESProcessResult result = new uMESProcessResult() { Message = msg, Result = res, DBTable = dt };
        return JsonConvert.SerializeObject(result);
    }

    /// <summary>
    /// 返回提示消息(数据对象)
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    private string ResMessage(object obj)
    {
        return JsonConvert.SerializeObject(obj);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}